package ${escapeKotlinIdentifiers(packageName)}.api.interceptor

import java.io.IOException

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.HttpUrl

class AuthTokenInterceptor() : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()

        val requestWithUserAgent = originalRequest.newBuilder()
         								  .header("Connection", "Close")
        							      .build()
        val originalResponse = chain.proceed(requestWithUserAgent)
        if (originalResponse.code() in CODE_REDIRECT_START..CODE_REDIRECT_END) {
            val redirectUrl = originalResponse.header("Location")
            originalResponse.body()?.close()

            return chain.proceed(originalRequest.newBuilder()
        							      .url(HttpUrl.parse(redirectUrl))
                                          .header("Connection", "Close")
        							      .build())
        }

        return originalResponse
    }

    companion object {
        @JvmField
        val CODE_REDIRECT_START = 300
        @JvmField
        val CODE_REDIRECT_END = 307
    }
}